﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using Se.Framework.Common.Data;
using Se.Framework.Common.Security;

namespace Se.Framework.Web.Security
{
    public class WebRoleManager : IRoleManager, IRepository<string>
    {
        public bool Exists(string roleName)
        {
            return Roles.RoleExists(roleName);
        }

        public IEnumerable<string> GetAll()
        {
            return Roles.GetAllRoles();
        }

        public bool IRoleManager(string name)
        {
            return Roles.RoleExists(name);
        }

        public bool Create(string name)
        {
            Roles.CreateRole(name);

            return true;
        }

        public bool Delete(string roleName)
        {
            return Roles.DeleteRole(roleName);
        }

        public bool IsInRole(string name, string role)
        {
            return Roles.IsUserInRole(name, role);
        }

        public void AddUserToRole(string name, string role)
        {
            Roles.AddUserToRole(name, role);
        }

        #region IRepository
        IQueryable<string> IRepository<string>.Query()
        {
            return GetAll().AsQueryable();
        }

        void IRepository<string>.Add(string entity)
        {
            Create(entity);
        }

        void IRepository<string>.Update(string entity)
        {
            throw new InvalidOperationException();
        }

        void IRepository<string>.Delete(string entity)
        {
            ((IRoleManager)this).Delete(entity);
        }

        string IRepository<string>.Find(params object[] keyValues)
        {
            if (Exists(keyValues[0].ToString()))
            {
                return keyValues[0].ToString();
            }
            return null;
        }
        #endregion
    }
}
